package xrate

import (
	"time"

	"gitee.com/xiaoyutab/xgotool/optional/xcache"
	"gitee.com/xiaoyutab/xgotool/xerror"
)

// 获取批次奖品列表
//
//	id	批次ID
func RateBatch(id uint) ([]RateWain, error) {
	// 获取批次详情
	batch, err := BatchInfo(id)
	if err != nil {
		return nil, err
	}
	if batch.Status != 1 {
		return nil, xerror.New("该批次暂无法抽奖")
	}
	// 声明奖池
	rate_wains := []RateWain{}
	cache_key := xcache.Key("xrate.rate_batch", id)
	if xcache.Exists(cache_key) {
		if err := xcache.GetStruct(cache_key, &rate_wains); err == nil {
			return rate_wains, nil
		}
		rate_wains = []RateWain{}
	}
	// 获取星级
	count, start_list, err := StartList(id)
	if err != nil {
		return nil, err
	}
	// 获取奖品
	for si := 0; si < int(count); si++ {
		count, project_list, err := ProjectList(id, start_list[si].ID, 0, -1)
		if err != nil {
			return nil, err
		}
		if count <= 0 {
			continue
		}
		for i := 0; i < len(project_list); i++ {
			if project_list[i].Residue <= 0 {
				continue
			}
			// 奖品注入到奖池列表中
			rate_wains = append(rate_wains, RateWain{
				ID:         project_list[i].ID,
				Name:       project_list[i].Name,
				Rate:       start_list[si].Rate / float64(count) * project_list[i].Rate,
				StartId:    project_list[i].StartID,  // 星级ID
				StartCount: start_list[si].Guarantee, // 星级保底ID
			})
		}
	}
	if len(rate_wains) == 0 {
		return nil, xerror.New("奖品为空")
	}
	xcache.SetStructExt(cache_key, rate_wains, time.Minute) // 缓存1分钟，避免库存爆炸
	return rate_wains, nil
}
